// 事件监听与销毁
// hooks/useEvents.ts
import { useEffect } from 'react';

type EventType = 'click' | 'moveend' | 'zoomchange';
type EventHandler = (event: any) => void;

export const useMapEvents = (
  map: AMap.Map | null,
  events: { [key in EventType]?: EventHandler }
) => {
  useEffect(() => {
    if (!map) return;

    const listeners: Array<{ type: EventType; handler: EventHandler }> = [];

    Object.entries(events).forEach(([type, handler]) => {
      if (handler) {
        map.on(type as EventType, handler);
        listeners.push({ type: type as EventType, handler });
      }
    });

    return () => {
      listeners.forEach(({ type, handler }) => map.off(type, handler));
    };
  }, [map, events]);
};